// scripts/login.js 
// 登录页面中的脚本文件
$(function(){
	//在页面加载完毕执行的脚本
	//console.log("OK");
	$('#login').click(loginAction);
	$('#count').focus().blur(checkUsername);
	$('#password').blur(checkPassword);
	
	//绑定注册界面的事件
	$('#regist_button').click(registAction);
	
});

function registAction(){
	console.log('registAction');
	//表单数据检验...
	var url='user/regist.do';
	var param={
		name: $('#regist_username').val(),
		nick: $('#nickname').val(),
		password: $('#regist_password').val(),
		confirm: $('#final_password').val()
	};
	console.log(param);
	//发起Ajax请求
	$.post(url, param, function(result){
		if(result.state==0){
			console.log(result);
			console.log('注册成功!');
			var user=result.data;
			//注册成功以后跳到登录页面
			$('#back').click();
			$('#count').val(user.name);
			$('#count-msg').empty();
			$('#password').focus();
		}else if(result.state==2){
			$('#warning_1 span')
				.html(result.message);
			$('#warning_1').show();
		}else if(result.state==3){
			$('#warning_2 span')
				.html(result.message);
			$('#warning_2').show();
		}else{
			alert(result.message);
		}
	});
}

function checkUsername(){
	//console.log('checkUsername');
	var name=$('#count').val();
	if(! name){
		$('#count-msg').empty().html('不能为空');
		return false;
	}
	var reg=/^\w{3,10}$/;
	if(reg.test(name)){
		$('#count-msg').empty();
		return true;
	}else{
		$('#count-msg').empty().html('必须3~10字母');
		return false;
	}
}

function checkPassword(){
	console.log('checkPassword');
	var pwd = $('#password').val();
	if(! pwd){
		$('#password-msg').html('不能空');
		return false;
	}
	var reg=/^\w{3,10}$/;
	//console.log(pwd);
	//console.log(reg.test(pwd));
	if(reg.test(pwd)){
		$('#password-msg').empty();
		return true;
	}else{
		$('#password-msg').html('3~10位');
		return false;
	}
}

function loginAction(){
	
	if(checkPassword()+checkUsername()!=2){
		return;
	}
	
	console.log('Login click');
	//获取表单中的参数
	//将表单参数利用AJAX发送到控制器
	//检查控制器返回值,如果state==0成功转edit.html
	var username=$('#count').val();
	var password=$('#password').val();
	
	console.log(username);
	console.log(password);
	
	var url='user/login.do';
	var param={name:username, 
			password:password};
	console.log(param);
	$.post(url, param, function(result){
		if(result.state==0){
			console.log('登录成功!');
			console.log(result.data);
			//登录成功以后保存userid到cookie
			var user = result.data;
			setCookie('userId', user.id);
			//调整到edit.html页面
			location.href='edit.html';
		}else if(result.state==2){
			//用户名错误
			$('#count-msg').html(
					result.message);
		}else if(result.state==3){
			//密码错误
			$('#password-msg').html(
					result.message);
		}else{
			//其他错误
			alert(result.message);
		}
	});
}




